package cn.hxzy.controller;


import cn.hxzy.common.OcrClient;
import cn.hxzy.common.OssUtil;

import cn.hxzy.common.ALiYunOSSProperties;
import cn.hxzy.common.Result;
import cn.hxzy.entity.IdCardBack;
import cn.hxzy.entity.IdCardFace;
import cn.hxzy.entity.accreditation.TsRealNameAuthentication;
import cn.hxzy.entity.vo.RealNameVo;
import cn.hxzy.service.TsRealNameAuthenticationService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import com.aliyun.ocr20191230.Client;
import com.aliyun.ocr20191230.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Date;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Kuizhi.Ma
 * @since 2023-06-25
 */
@RestController
@CrossOrigin
@RequestMapping("/tsRealNameAuthentication")
public class TsRealNameAuthenticationController {

    @Autowired
    private TsRealNameAuthenticationService tsRealNameAuthenticationService;

    @PostMapping("updateRealIdCard")
    public Result updateIdCard(@RequestBody TsRealNameAuthentication tsRealNameAuthentication) throws Exception {
        Result result = tsRealNameAuthenticationService.insertRealIdCard(
                tsRealNameAuthentication.getRegisterPhone(),
                tsRealNameAuthentication.getIdCardFront(),
                tsRealNameAuthentication.getIdCardOpposite()
        );
        return result;
    }




    @RequestMapping("getIdCardFace")
    public Result getIdCardFace(@RequestParam MultipartFile file) throws Exception {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        System.out.println("这是工具类返回的身份证反面图片路径-- " + ossUrl);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();
        IdCardFace idCardFace1 = recognizeIdCardAdvanceFace(client, ossUrl);
//        性别字符串转换
        if (idCardFace1.getGender().equals("男")) {
            idCardFace1.setGender("101");
        } else {
            idCardFace1.setGender("102");
        }
//        出生日期转化String转Date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date parse = sdf.parse(idCardFace1.getBirthDates());
        idCardFace1.setBirthDate(parse);
//        正面图片路径
        idCardFace1.setIdCardFront(ossUrl);
        System.out.println(parse);
        System.out.println("这是实名认证正面信息-- " + idCardFace1);

        return Result.ok().data1(idCardFace1);
    }

    @RequestMapping("getIdCardBack")
    public Result getIdCardBack(@RequestParam MultipartFile file) throws Exception {
        //        调用工具类返回的图片路径
        String ossUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        System.out.println("这是工具类返回的身份证反面图片路径-- " + ossUrl);
        //        OCR验证的客户端
        Client client = OcrClient.getOCRClient();
        IdCardBack idCardBack = recognizeIdCardAdvanceBack(client, ossUrl);
//        反面图片路径
        idCardBack.setIdCardOpposite(ossUrl);
//        返回身份失效时间段
        String startDate = idCardBack.getStartDate();
        String startYear = startDate.substring(0, 4);
        String startMonth = startDate.substring(4, 6);
        String startDay = startDate.substring(6, 8);
        String endDate = idCardBack.getEndDate();
        String endYear = endDate.substring(0, 4);
        String endMonth = endDate.substring(4, 6);
        String endDay = endDate.substring(6, 8);
        idCardBack.setValidPeriod(startYear + "-" + startMonth + "-" + startDay + "-" + endYear + "-" + endMonth + "-" + endDay);
        System.out.println(idCardBack.getValidPeriod());

//        idCardBack.setValidPeriod();
        System.out.println("这是实名认证反面信息-- " + idCardBack);
        return Result.ok().data1(idCardBack);
    }

    //   身份证--正
    private static IdCardFace recognizeIdCardAdvanceFace(Client client, String ossUrl) throws Exception {
        RecognizeIdentityCardRequest recognizeIdentityCardRequest = new RecognizeIdentityCardRequest()
                .setImageURL(ossUrl)
                .setSide("face");
        RuntimeOptions runtime = new RuntimeOptions();
        IdCardFace idCardFace = new IdCardFace();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeIdentityCardResponse recognizeIdentityCardResponse = client.recognizeIdentityCardWithOptions(recognizeIdentityCardRequest, runtime);
//            籍贯
            idCardFace.setAddress(recognizeIdentityCardResponse.getBody().getData().getFrontResult().address);
//            出生日期
            idCardFace.setBirthDates(recognizeIdentityCardResponse.getBody().getData().getFrontResult().birthDate);
//            性别
            idCardFace.setGender(recognizeIdentityCardResponse.getBody().getData().getFrontResult().gender);
//            身份证号
            idCardFace.setIdNumber(recognizeIdentityCardResponse.getBody().getData().getFrontResult().IDNumber);
//            姓名
            idCardFace.setName(recognizeIdentityCardResponse.getBody().getData().getFrontResult().name);
//            民族
            idCardFace.setNationality(recognizeIdentityCardResponse.getBody().getData().getFrontResult().nationality);

        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        }
        return idCardFace;
    }

    //    身份证--反
    private static IdCardBack recognizeIdCardAdvanceBack(Client client, String ossUrl) throws Exception {
        RecognizeIdentityCardRequest recognizeIdentityCardRequest = new RecognizeIdentityCardRequest()
                .setImageURL(ossUrl)
                .setSide("back");
        RuntimeOptions runtime = new RuntimeOptions();
        IdCardBack idCardFace = new IdCardBack();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeIdentityCardResponse recognizeIdentityCardResponse = client.recognizeIdentityCardWithOptions(recognizeIdentityCardRequest, runtime);
//            籍贯
            idCardFace.setEndDate(recognizeIdentityCardResponse.getBody().getData().getBackResult().endDate);
//            出生日期
            idCardFace.setIssue(recognizeIdentityCardResponse.getBody().getData().getBackResult().issue);
//            性别
            idCardFace.setStartDate(recognizeIdentityCardResponse.getBody().getData().getBackResult().startDate);

        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        }
        return idCardFace;
    }

    //    身份证认证信息
    @RequestMapping("insertRealName")
    private Result insertRealName(@RequestBody RealNameVo realNameVo) {
//        给认证身份证分配认证ID
//        realNameVo.setAuthenticationId();
//        给认证身份证分配用户编号

        return Result.ok().data1(1111);
    }
}

